package edu.hrbu.trade01.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.hrbu.trade01.entity.OperLog;
import edu.hrbu.trade01.mapper.OperLogMapper;
import edu.hrbu.trade01.service.OperLogService;
import edu.hrbu.trade01.vo.AnalysisVo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static edu.hrbu.trade01.util.ConstUtil.*;

/**
 * @author 徐登宇
 */
@Service
public class OperLogServiceImpl extends ServiceImpl<OperLogMapper, OperLog> implements OperLogService {
    // 条件分页查询
    @Override
    public Page<OperLog> getPageWithCondition(int page, int limit, String logStr) {
        Page<OperLog> pageParam = new Page<>(page, limit);
        LambdaQueryWrapper<OperLog> wrapperLog = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(logStr)) {
            OperLog operLog = JSONUtil.toBean(logStr, OperLog.class);
            if (operLog!=null) {
                String title = operLog.getTitle();
                String businessType = operLog.getBusinessType();
                String status = operLog.getStatus();
                String operName = operLog.getOperName();
                if (!ObjectUtils.isEmpty(title)){
                    wrapperLog.like(OperLog::getTitle,title);
                }
                if (!ObjectUtils.isEmpty(businessType)){
                    wrapperLog.eq(OperLog::getBusinessType,businessType);
                }
                if (!ObjectUtils.isEmpty(status)){
                    wrapperLog.eq(OperLog::getStatus,status);
                }
                if (!ObjectUtils.isEmpty(operName)){
                    wrapperLog.like(OperLog::getOperName,operName);
                }
            }
        }
        Page<OperLog> pageModel = page(pageParam, wrapperLog);
        return pageModel;
    }

    @Override
    public List<AnalysisVo> analysis() {
        AnalysisVo firm=new AnalysisVo(LOG_TYPE_FIRM, count(new LambdaQueryWrapper<OperLog>().eq(OperLog::getBusinessType, LOG_TYPE_FIRM)));
        AnalysisVo sys=new AnalysisVo(LOG_TYPE_SYS, count(new LambdaQueryWrapper<OperLog>().eq(OperLog::getBusinessType, LOG_TYPE_SYS)));
        AnalysisVo profession=new AnalysisVo(LOG_TYPE_PROFESSION, count(new LambdaQueryWrapper<OperLog>().eq(OperLog::getBusinessType, LOG_TYPE_PROFESSION)));
        AnalysisVo news=new AnalysisVo(LOG_TYPE_NEWS, count(new LambdaQueryWrapper<OperLog>().eq(OperLog::getBusinessType, LOG_TYPE_NEWS)));

        return new ArrayList<AnalysisVo>(Arrays.asList(firm, sys, profession, news));
    }
}
